﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.QC;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.DTO.QC;
using KWT.DRG_DIP.PO.Basic;
using KWT.DRG_DIP.PO.QC;
using KWT.DRG_DIP.PO.Settlement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using OfficeOpenXml;
using System.Text;
using Yitter.IdGenerator;

namespace KWT.DRG_DIP.API.Controllers.QC
{
    /// <summary>
    /// 质控
    /// </summary>
    [ApiExplorerSettings(GroupName = "qc")]
    public class ErrController : QCControllerBase
    {
        public EFContext ef { get; set; }
        private readonly IHttpClientFactory _qc_http;

        public ErrController(IHttpClientFactory qc_http)
        {
            _qc_http = qc_http;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult PageList(InPageList dto)
        {
            var q = ef.Set<Sys_QC_Err>().AsQueryable();
            if (!string.IsNullOrEmpty(dto.ErrCode))
            {
                q = q.Where(x => EF.Functions.Like(x.ErrCode, $"%{dto.ErrCode}%"));
            }
            if (!string.IsNullOrEmpty(dto.Msg))
            {
                q = q.Where(x => EF.Functions.Like(x.Msg, $"%{dto.Msg}%"));
            }
            if (dto.Type > 0)
            {
                q = q.Where(x => x.Type == dto.Type);
            }
            if (!string.IsNullOrEmpty(dto.ErrCode))
            {
                q = q.Where(x => EF.Functions.Like(x.ErrCode, $"%{dto.ErrCode}%"));
            }
            int total = q.Count();
            var list = q.ToPageList(dto.PageNo, dto.PageSize);
            return Output(list.Count > 0, "", "", new PageList<Sys_QC_Err>() { List = list, Total = total });
        }

        /// <summary>
        /// 添加或编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult AddOrUpdate(InAddOrUpdate dto)
        {
            var err = _mapper.Map<Sys_QC_Err>(dto);
            if (!ef.Set<Sys_QC_Err>().Any(x => x.ErrID == dto.ErrID))
            {
                ef.Add(err);
            }
            else
            {
                ef.Update(err);
            }
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="errIDs"></param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult Del([FromQuery] string[] errIDs)
        {
            var flag = ef.Set<Sys_QC_Err>().Where(x => errIDs.Contains(x.ErrID)).ExecuteDelete() > 0;
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="file">excel文件</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Import(IFormFile file)
        {
            using var pkg = new ExcelPackage(file.OpenReadStream());
            var worksheet = pkg.Workbook.Worksheets[0];

            var list = worksheet.Dimension.ToCollectionWithMappings(row =>
            {
                var para = new Sys_QC_Err
                {
                    ErrID = row.GetValue<string>("错误ID"),
                    ErrCode = row.GetValue<string>("错误编码"),
                    Msg = row.GetValue<string>("错误信息"),
                    Score = row.GetValue<decimal>("分值"),
                    Type = row.GetValue<int>("类别"),
                };
                return para;
            }, options => options.HeaderRow = 0);
            ef.AddRange(list);
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 切换患者信息时质控
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<OutputResult> FromPlugin(WT4 dto)
        {
            var http = _qc_http.CreateClient("QC");
            string qc_url = _Config.GetValue<string>("qc_url");
            var rqs = JsonConvert.SerializeObject(dto);
            var rsp = await http.PostAsync(qc_url, new StringContent(rqs, Encoding.UTF8, "application/json"));
            if (rsp.IsSuccessStatusCode)
            {
                var result = await rsp.Content.ReadAsStringAsync();

                var dic = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(result);
                var _r = dic.TryGetValue("__RESULT__", out string[] val);
                if (_r)
                {
                    if (!val[0].Equals("SUCCESS"))
                    {
                        return Fail("质控出错，请重试！");
                    }
                    else
                    {
                        var qcItems = new List<QC_Err_Item>();
                        foreach (var property in dic.Keys)
                        {
                            if (!property.StartsWith('_'))
                            {
                                if (dic.TryGetValue(property, out string[] errCodes))
                                {
                                    foreach (var code in errCodes)
                                    {
                                        var qcItem = new QC_Err_Item() { Property = property };
                                        qcItem.ErrCode = code;
                                        qcItems.Add(qcItem);
                                    }
                                }
                            }
                        }

                        var errList = ef.Set<Sys_QC_Err>().Where(x => qcItems.Select(y => y.ErrCode).Contains(x.ErrCode))
                                        .Select(x => new { x.ErrCode, x.Msg }).AsNoTracking().ToList();
                        var enumList = ef.Set<Sys_Enum>().Where(x => x.Group == "卫统4").AsNoTracking().ToList();
                        var _result = (from x in qcItems
                                       join y in errList on x.ErrCode equals y.ErrCode
                                       join z in enumList on x.Property equals z.Value
                                       select new { x.Property, x.ErrCode, y.Msg, PropertyName = z.Text }).ToList();
                        return Output(true, "", "", _result);
                    }
                }
                else
                {
                    return Fail("响应JSON解析失败！");
                }
            }
            else
            {
                return Fail("质控出错，质控服务器发生非200状态码错误，请重试！");
            }
        }


    }
}
